#include "my_stdio.h"
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define FILE_MODE 0666

// "w" "a" "r"
_FILE* _fopen(const char* filename, const char* flag)
{
    int f = 0;
    if (strcmp(flag, "w") == 0)
        f = (O_CREAT | O_WRONLY | O_TRUNC);
    else if (strcmp(flag, "a") == 0)
        f = (O_CREAT | O_WRONLY | O_APPEND);
    else if (strcmp(flag, "r") == 0)
        f = O_RDONLY;
    else
        return NULL;
    
    int fd = open(filename, f, FILE_MODE);
    if (fd == -1)
        return NULL;
    _FILE* fp = (_FILE*)malloc(sizeof(_FILE*));
    if (fp == NULL)
        return NULL;

    fp->fileno = fd;
    fp->flag = FLUSH_LINE;
    fp->outpos = 0;
    return fp;
}

int _fwrite(_FILE* fp, const char* s, int len)
{
    memcpy(fp->outbuffer + fp->outpos, s, len);
    fp->outpos += len;

    if (fp->flag & FLUSH_NOW)
    {
        write(fp->fileno, fp->outbuffer, fp->outpos);
        fp->outpos = 0;
    }
    else if (fp->flag & FLUSH_LINE)
    {
        if (fp->outbuffer[fp->outpos - 1] == '\n')
        {
            write(fp->fileno, fp->outbuffer, fp->outpos);
            fp->outpos = 0;
        }
    }
    else if (fp->flag & FLUSH_ALL)
    {
        if (fp->outpos == BUF_SIZE)
        {
            write(fp->fileno, fp->outbuffer, fp->outpos);
            fp->outpos = 0;
        }
    }
    return len;
}

void _fflush(_FILE* fp)
{
    if (fp->outpos > 0)
    {
        write(fp->fileno, fp->outbuffer, fp->outpos);
        fp->outpos = 0;
    }
}

void _fclose(_FILE* fp)
{
    if (fp == NULL)
        return;
    if (fp->outpos > 0)
        _fflush(fp);
    close(fp->fileno);
    free(fp);
}
